package com.cjm.algorithm.leetcode;

import com.cjm.algorithm.ListNode;
import com.cjm.algorithm.ListNodeHelp;

public class RemoveNthFromEnd19 {
    public static ListNode removeNthFromEnd1(ListNode head, int n) {
        int index = 1;
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode cur = head;
        while (index < n + 1) {
            cur = cur.next;
            index++;
        }
        while (cur != null) {
            cur = cur.next;
            pre = pre.next;
        }

        ListNode del = pre.next;
        ListNode next = del.next;
        pre.next = next;
        return dummyNode.next;
    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int index = 1;
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode cur = head;
        while (index < n + 1) {
            cur = cur.next;
            index++;
        }

        while (cur != null) {
            cur = cur.next;
            pre = pre.next;
        }

        ListNode del = pre.next;
        ListNode next = del.next;
        pre.next = next;
        return dummyNode.next;
    }

    public static void main(String[] args) {
        ListNodeHelp.printListNode(removeNthFromEnd(ListNodeHelp.toListNode(new int[]{1, 2, 3, 4, 5}), 2));
    }
}
